package middleware

import (
	"context"
	"net/http"

	"ruikc.com/server/api/internal/config"
	"ruikc.com/server/utils"
)

type UserMiddleware struct {
	config config.Config
}

func NewUserMiddleware(c config.Config) *UserMiddleware {
	return &UserMiddleware{
		config: c,
	}
}

func (m *UserMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		AccessToken := r.Header.Get("Authorization")
		if AccessToken == "" {
			http.Error(w, "登录超时，请重新登录", http.StatusUnauthorized)
			return
		}
		jwtUser, err := utils.ParseTokenHs256(AccessToken, m.config.Auth.AccessSecret)
		if err != nil {
			http.Error(w, "登录超时，请重新登录", http.StatusUnauthorized)
			return
		}
		reqCtx := r.Context()
		ctx := context.WithValue(reqCtx, "jwt_user", jwtUser)
		newReq := r.WithContext(ctx)
		next(w, newReq)
	}
}
